// 对于Deno，不需要显式导入crypto，它是全局可用的
// import * as crypto from "crypto";

// 模拟auth.ts中的密钥
const SECRET_KEY = "my-fresh-blog-super-secret-and-long-key-!@#$%^&*()";

// 会话数据结构
interface UserSession {
  userId: number;
  username: string;
  displayName: string;
  avatarUrl: string | null;
  role: string;
  timestamp: number;
}

// 模拟签名函数
async function signData(data: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(SECRET_KEY),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"]
  );
  const signature = await crypto.subtle.sign(
    "HMAC", 
    key, 
    new TextEncoder().encode(data)
  );
  return Array.from(new Uint8Array(signature))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

// 模拟验证签名函数
async function verifySignedData(data: string, signatureToVerify: string): Promise<boolean> {
  try {
    const expectedSignature = await signData(data);
    return expectedSignature === signatureToVerify;
  } catch (e) {
    console.error("Error during signature verification:", e);
    return false;
  }
}

// 创建测试cookie
async function createDebugCookie() {
  console.log("创建调试用的cookie值...");
  
  // 测试会话数据
  const sessionData: UserSession = {
    userId: 1,
    username: "admin",
    displayName: "管理员",
    avatarUrl: null,
    role: "admin",
    timestamp: Date.now()
  };
  
  const sessionDataStr = JSON.stringify(sessionData);
  console.log("会话数据:", sessionDataStr);
  
  // 计算签名
  const signature = await signData(sessionDataStr);
  console.log("签名:", signature);
  
  // URL编码会话数据
  const encodedSessionData = encodeURIComponent(sessionDataStr);
  console.log("URL编码会话数据:", encodedSessionData);
  
  // 生成完整cookie值
  const cookieValue = `${encodedSessionData}.${signature}`;
  console.log("\n完整Cookie值 (可以手动设置到浏览器):");
  console.log("admin_session_token_v3=" + cookieValue);
  
  // 解析并验证cookie
  console.log("\n测试解析cookie值...");
  await parseAndVerifyCookie(cookieValue);
}

// 解析和验证cookie
async function parseAndVerifyCookie(cookieValue: string) {
  try {
    const [encodedSessionDataStr, signature] = cookieValue.split('.');
    
    if (!encodedSessionDataStr || !signature) {
      console.error("无效的cookie格式");
      return;
    }
    
    console.log("从cookie中提取签名:", signature);
    const sessionDataStr = decodeURIComponent(encodedSessionDataStr);
    console.log("URL解码后的会话数据:", sessionDataStr);
    
    const isValid = await verifySignedData(sessionDataStr, signature);
    console.log("签名验证结果:", isValid ? "有效" : "无效");
    
    if (isValid) {
      const userData = JSON.parse(sessionDataStr) as UserSession;
      console.log("解析的用户数据:", userData);
    }
  } catch (error) {
    console.error("解析cookie时出错:", error);
  }
}

// 运行调试工具
if (import.meta.main) {
  await createDebugCookie();
} 